package com.bhs.sansonglogistics.ui.other;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bhs.sansonglogistics.R;
import com.bhs.sansonglogistics.base.BaseFragment;
import com.bhs.sansonglogistics.bean.CompanyReportNum;
import com.bhs.sansonglogistics.bean.DataBoardBean;
import com.bhs.sansonglogistics.bean.OrderGoodsItem;
import com.bhs.sansonglogistics.bean.event.Event;
import com.bhs.sansonglogistics.net.NetCallBack;
import com.bhs.sansonglogistics.ui.home.MainActivity;
import com.bhs.sansonglogistics.ui.message.VisitorLogActivity;
import com.bhs.sansonglogistics.ui.mine.MyRevenueActivity;
import com.bhs.sansonglogistics.ui.order.HistoryOrderActivity;
import com.bhs.sansonglogistics.utils.DateUtils;
import com.bhs.sansonglogistics.view.MyMarkerView;
import com.bhs.sansonglogistics.view.MyMarkerView2;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * 数据看板-我的
 */
public class DataBoardMineFragment extends BaseFragment implements NetCallBack {

    private RecyclerView mRvList;
    private List<DataBoardBean> mList = new ArrayList<>();
    private BaseQuickAdapter<DataBoardBean, BaseViewHolder> mAdapter;
    private LineChart line;

    public static DataBoardMineFragment newInstance() {
        return new DataBoardMineFragment();
    }

    @Override
    public int initLayout() {
        return R.layout.fragment_data_board_mine;
    }

    @Override
    public void initView(View root) {
        mRvList = root.findViewById(R.id.rv_list);
        line = root.findViewById(R.id.line);
        line.setNoDataText("暂无数据");   // 没有数据时样式
        mList.add(new DataBoardBean(R.mipmap.ic_gross_amount, "接单总金额(元)"));
        mList.add(new DataBoardBean(R.mipmap.ic_order_receivin_number, "接单总数量(笔)"));
        mList.add(new DataBoardBean(R.mipmap.ic_preempt_money, "抢单总金额(元)"));
        mList.add(new DataBoardBean(R.mipmap.ic_preempt_number, "抢单总数量(笔)"));
        mList.add(new DataBoardBean(R.mipmap.ic_refuse_an_order, "拒绝(笔)"));
       // mList.add(new DataBoardBean(R.mipmap.ic_cancel_number, "取消(笔)"));
        mList.add(new DataBoardBean(R.mipmap.ic_visitor_distance, "访客记录"));
        mList.add(new DataBoardBean(R.mipmap.ic_call_me, "联系我"));
        mList.add(new DataBoardBean(R.mipmap.ic_collect_me, "收藏我的"));
        mAdapter = new BaseQuickAdapter<DataBoardBean, BaseViewHolder>(R.layout.item_brief_work_reports, mList) {
            @Override
            protected void convert(@NonNull BaseViewHolder helper, DataBoardBean item) {
                helper.setImageResource(R.id.iv_icon, item.getIcon());
                helper.setText(R.id.tv_explain, item.getExplain());
                helper.setText(R.id.tv_value, TextUtils.isEmpty(item.getValue()) ? "0" : item.getValue());
            }
        };
        mRvList.setAdapter(mAdapter);
        mRvList.setLayoutManager(new GridLayoutManager(getContext(), 2));
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (position == 4) {
                    startActivity(new Intent(getContext(), HistoryOrderActivity.class)
                            .putExtra("item", 1));
                } else if (position == 5) {
                    startActivity(new Intent(getContext(), VisitorLogActivity.class));
                } else if (position == 6) {
                    startActivity(new Intent(getContext(), VisitorLogActivity.class)
                            .putExtra("item", 1));
                } else if (position == 7) {

                } else if (position == 0) {
                    startActivity(new Intent(getContext(), MyRevenueActivity.class));
                }

//                else if (position == 5) {
//                    getActivity().finish();
//                    EventBus.getDefault().post(new Event(1));
//                    EventBus.getDefault().postSticky(new OrderGoodsItem(8));
//                }
            }
        });
    }

    List<Entry> list = new ArrayList<>();          //实例化一个 List  用来保存你的数据

    @Override
    public void initData() {
        loadingPopupShow();
        networkRequest(netApi.get_logistics_company_report_nums(), this);

    }


    @SuppressLint("NotifyDataSetChanged")
    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        loadingPopupDismiss();
        CompanyReportNum companyReportNum = new Gson().fromJson(json, CompanyReportNum.class);
        if (companyReportNum.isStatus()) {
            CompanyReportNum.DataDTO data = companyReportNum.getData();
            mList.get(0).setValue(data.getTotal_money());
            mList.get(1).setValue(data.getTotal_num());
            mList.get(2).setValue(data.getRob_money());
            mList.get(3).setValue(data.getRob_num());
            mList.get(4).setValue(data.getReject_num());
           // mList.get(5).setValue(data.getCancel_num());
            mList.get(5).setValue(data.getVisitor_num());
            mList.get(6).setValue(data.getContact_num());
            mList.get(7).setValue(data.getCollect_num());
            mAdapter.notifyDataSetChanged();
            lineChart(companyReportNum.getData().getOrder_list());
        }
    }

    private void lineChart(List<CompanyReportNum.DataDTO.OrderListDTO> order_list) {

        for (int i = 0; i < order_list.size(); i++) {
            list.add(new Entry(i, order_list.get(i).getNum()));
        }

        //list是你这条线的数据  "语文" 是你对这条线的描述（也就是图例上的文字）
        LineDataSet lineDataSet = new LineDataSet(list, "");
        LineData lineData = new LineData(lineDataSet);
        line.setData(lineData);
        XAxis xAxis = line.getXAxis();
        xAxis.setDrawGridLines(false);  //是否绘制X轴上的网格线（背景里面的竖线）
        //   X轴所在位置   默认为上面
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                return DateUtils.getMonthDay(order_list.get((int) value).getDate());
            }
        });
        line.setScaleEnabled(false);
        line.getDescription().setEnabled(false);                  //是否显示右下角描述
        //图例
        Legend legend = line.getLegend();
        legend.setEnabled(false);    //是否显示图例
        lineDataSet.setColor(Color.parseColor("#979797"));  //折线的颜色
        //是否画折线点上的空心圆  false表示直接画成实心圆
        lineDataSet.setDrawCircleHole(false);
        lineDataSet.setCircleColor(Color.parseColor("#979797"));
        lineDataSet.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                return String.valueOf((int) value);
            }
        });
        lineDataSet.setDrawValues(true);
        MyMarkerView2 mv = new MyMarkerView2(getContext(), R.layout.custom_marker_view2, order_list);
        mv.setChartView(line);
        line.setMarker(mv);

        //隐藏右边的Y轴
        line.getAxisRight().setEnabled(false);
        line.getAxisLeft().setDrawAxisLine(false);
        line.setBorderColor(Color.GREEN); // 边框颜色
        line.invalidate();

    }

    @Override
    public void onFailure(int requestCode) {
        loadingPopupDismiss();
    }
}